<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI易经出行 v4.0.1 - 智能运势分析</title>
    <style>
        /* CSS变量定义 */
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --accent-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            --success-color: #27ae60;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --info-color: #3498db;
            --text-light: #ecf0f1;
            --text-dark: #2c3e50;
            --shadow: 0 10px 30px rgba(0,0,0,0.3);
            --shadow-light: 0 5px 15px rgba(0,0,0,0.1);
            --border-radius: 15px;
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: var(--primary-gradient);
            color: var(--text-light);
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* 背景动画 */
        .bg-animation {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background: var(--primary-gradient);
        }

        .bg-animation::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
            background-size: 50px 50px;
            animation: float 20s infinite linear;
        }

        @keyframes float {
            0% { transform: translate(0, 0) rotate(0deg); }
            100% { transform: translate(-50px, -50px) rotate(360deg); }
        }

        /* 主容器 */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            position: relative;
            z-index: 1;
        }

        /* 头部区域 */
        .header {
            text-align: center;
            margin-bottom: 30px;
            animation: fadeInDown 1s ease-out;
        }

        .header h1 {
            font-size: 2.5rem;
            font-weight: 300;
            margin-bottom: 10px;
            background: var(--accent-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.8;
        }

        /* 时间信息卡片 */
        .time-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: var(--shadow-light);
            animation: fadeInUp 1s ease-out 0.2s both;
        }

        .time-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
        }

        .time-item {
            text-align: center;
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .time-label {
            font-size: 0.9rem;
            opacity: 0.7;
            margin-bottom: 8px;
        }

        .time-value {
            font-size: 1.2rem;
            font-weight: 600;
        }

        /* 罗盘选择器 */
        .compass-container {
            display: flex;
            justify-content: center;
            margin: 40px 0;
            animation: fadeInUp 1s ease-out 0.4s both;
        }

        .compass {
            position: relative;
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background: conic-gradient(
                from 0deg,
                #e74c3c 0deg 45deg,    /* 东 - 红色 */
                #f39c12 45deg 90deg,   /* 东南 - 橙色 */
                #27ae60 90deg 135deg,  /* 南 - 绿色 */
                #2ecc71 135deg 180deg, /* 西南 - 浅绿 */
                #3498db 180deg 225deg, /* 西 - 蓝色 */
                #9b59b6 225deg 270deg, /* 西北 - 紫色 */
                #e91e63 270deg 315deg, /* 北 - 粉色 */
                #ff6b6b 315deg 360deg  /* 东北 - 珊瑚色 */
            );
            box-shadow: var(--shadow);
            transition: var(--transition);
            cursor: pointer;
        }

        .compass:hover {
            transform: scale(1.05);
        }

        .compass-center {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100px;
            height: 100px;
            background: var(--dark-gradient);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            font-weight: bold;
            box-shadow: inset 0 0 20px rgba(0,0,0,0.3);
            z-index: 3;
        }

        .compass-needle {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 3px;
            height: 100px;
            background: linear-gradient(to bottom, #fff 0%, #fff 60%, transparent 60%);
            transform-origin: center bottom;
            transform: translate(-50%, -100%);
            transition: var(--transition);
            z-index: 2;
            border-radius: 2px;
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
        }

        .compass-directions {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .direction-label {
            position: absolute;
            font-weight: bold;
            font-size: 1.1rem;
            text-shadow: 0 0 10px rgba(0,0,0,0.5);
            cursor: pointer;
            transition: var(--transition);
        }

        .direction-label:hover {
            transform: scale(1.2);
        }

        /* 方向标签位置 */
        .direction-label:nth-child(1) { top: 10px; left: 50%; transform: translateX(-50%); } /* 北 */
        .direction-label:nth-child(2) { top: 50%; right: 10px; transform: translateY(-50%); } /* 东 */
        .direction-label:nth-child(3) { bottom: 10px; left: 50%; transform: translateX(-50%); } /* 南 */
        .direction-label:nth-child(4) { top: 50%; left: 10px; transform: translateY(-50%); } /* 西 */
        .direction-label:nth-child(5) { top: 20%; right: 20%; } /* 东北 */
        .direction-label:nth-child(6) { top: 20%; left: 20%; } /* 西北 */
        .direction-label:nth-child(7) { bottom: 20%; right: 20%; } /* 东南 */
        .direction-label:nth-child(8) { bottom: 20%; left: 20%; } /* 西南 */

        /* 结果显示区域 */
        .result-container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 30px;
            margin: 30px 0;
            box-shadow: var(--shadow-light);
            animation: fadeInUp 1s ease-out 0.6s both;
        }

        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid rgba(255, 255, 255, 0.2);
        }

        .direction-title {
            font-size: 1.8rem;
            font-weight: 600;
        }

        .jx-badge {
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            font-size: 1.1rem;
            min-width: 80px;
            text-align: center;
            transition: var(--transition);
        }

        .jx-badge.ji {
            background: var(--success-color);
            color: white;
            box-shadow: 0 0 20px rgba(39, 174, 96, 0.5);
        }

        .jx-badge.xiong {
            background: var(--danger-color);
            color: white;
            box-shadow: 0 0 20px rgba(231, 76, 60, 0.5);
        }

        .result-content {
            margin: 20px 0;
            line-height: 1.8;
            font-size: 1.1rem;
        }

        .jie-method {
            margin-top: 20px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            border-left: 4px solid var(--info-color);
        }

        .jie-method h4 {
            margin-bottom: 10px;
            color: var(--info-color);
        }

        /* 数据可视化 */
        .visualization {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }

        .chart-container {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 20px;
            box-shadow: var(--shadow-light);
        }

        .chart-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 15px;
            text-align: center;
        }

        .energy-bar {
            width: 100%;
            height: 20px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .energy-fill {
            height: 100%;
            background: var(--accent-gradient);
            border-radius: 10px;
            transition: width 1s ease-out;
        }

        .elements-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;
            margin-top: 15px;
        }

        .element-item {
            text-align: center;
            padding: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            font-size: 0.9rem;
        }

        /* 功能区 */
        .function-area {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: var(--border-radius);
            padding: 30px;
            margin: 30px 0;
            box-shadow: var(--shadow-light);
            animation: fadeInUp 1s ease-out 0.8s both;
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-label {
            font-size: 1.1rem;
            margin-bottom: 10px;
            display: block;
        }

        .input-row {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        input[type="text"] {
            flex: 1;
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.1);
            color: var(--text-light);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            font-size: 1rem;
            transition: var(--transition);
        }

        input[type="text"]:focus {
            outline: none;
            border-color: var(--info-color);
            box-shadow: 0 0 20px rgba(52, 152, 219, 0.3);
        }

        input[type="text"]::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        button {
            padding: 15px 30px;
            background: var(--accent-gradient);
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: var(--transition);
            box-shadow: var(--shadow-light);
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }

        button:active {
            transform: translateY(0);
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        /* 动画定义 */
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .pulse {
            animation: pulse 2s infinite;
        }

        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 40px;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid var(--info-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .compass {
                width: 250px;
                height: 250px;
            }
            
            .compass-center {
                width: 80px;
                height: 80px;
                font-size: 1rem;
            }
            
            .input-row {
                flex-direction: column;
            }
            
            .visualization {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="bg-animation"></div>
    
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <h1>AI易经出行 v4.0.1</h1>
            <p>智能运势分析 · 多维度预测 · 可视化展示</p>
        </div>

        <!-- 时间信息 -->
        <div class="time-card">
            <div class="time-grid">
                <div class="time-item">
                    <div class="time-label">当前时间</div>
                    <div id="current-time" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">农历时辰</div>
                    <div id="shi-chen" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">黄道信息</div>
                    <div id="huang-dao" class="time-value">-</div>
                </div>
                <div class="time-item">
                    <div class="time-label">能量等级</div>
                    <div id="energy-level" class="time-value">-</div>
                </div>
            </div>
        </div>

        <!-- 罗盘选择器 -->
        <div class="compass-container">
            <div class="compass" id="compass">
                <div class="compass-needle" id="needle"></div>
                <div class="compass-center" id="center-text">选择方向</div>
                <div class="compass-directions">
                    <div class="direction-label" data-direction="北">北</div>
                    <div class="direction-label" data-direction="东">东</div>
                    <div class="direction-label" data-direction="南">南</div>
                    <div class="direction-label" data-direction="西">西</div>
                    <div class="direction-label" data-direction="东北">东北</div>
                    <div class="direction-label" data-direction="西北">西北</div>
                    <div class="direction-label" data-direction="东南">东南</div>
                    <div class="direction-label" data-direction="西南">西南</div>
                </div>
            </div>
        </div>

        <!-- 结果显示区域 -->
        <div class="result-container" id="result-container" style="display: none;">
            <div class="result-header">
                <div class="direction-title">方向: <span id="selected-direction">-</span></div>
                <div id="jx-badge" class="jx-badge">-</div>
            </div>
            <div id="result-content" class="result-content">
                请选择一个方向查看吉凶信息
            </div>
            <div class="jie-method">
                <h4>解挂方法</h4>
                <div id="jie-method">-</div>
            </div>
        </div>

        <!-- 数据可视化 -->
        <div class="visualization" id="visualization" style="display: none;">
            <div class="chart-container">
                <div class="chart-title">能量等级</div>
                <div class="energy-bar">
                    <div id="energy-fill" class="energy-fill" style="width: 0%"></div>
                </div>
                <div id="energy-text">0%</div>
            </div>
            
            <div class="chart-container">
                <div class="chart-title">五行分析</div>
                <div class="elements-grid" id="elements-grid">
                    <!-- 动态生成五行元素 -->
                </div>
            </div>
            
            <div class="chart-container">
                <div class="chart-title">开运建议</div>
                <div id="lucky-info">
                    <div id="lucky-colors"></div>
                    <div id="lucky-numbers"></div>
                    <div id="best-time"></div>
                </div>
            </div>
        </div>

        <!-- 功能区 -->
        <div class="function-area">
            <div class="input-group">
                <label class="input-label">个人信息分析（姓名、生日、联系方式等）</label>
                <div class="input-row">
                    <input type="text" id="info-input" placeholder="例如：姓名：张三，生日：1990-01-01，手机：13800138000">
                    <button id="analyze-btn">开始分析</button>
                </div>
            </div>
            <div class="input-row">
                <button id="refresh-btn" onclick="refreshData()">刷新数据</button>
                <button id="clear-cache-btn" onclick="clearCache()">清除缓存</button>
                <button id="batch-analyze-btn" onclick="batchAnalyze()">批量分析</button>
            </div>
        </div>
    </div>

    <script>
        // 内联API服务类，避免CORS问题
        class ApiService {
            // 缓存配置
            static CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存
            static cache = new Map();
            
            // API配置
            static API_CONFIG = {
                baseUrl: "https://api.siliconflow.cn/v1/chat/completions",
                model: "Qwen/Qwen2.5-7B-Instruct",
                timeout: 30000, // 30秒超时
                retryCount: 3   // 重试3次
            };

            /**
             * 调用AI易经出行API（增强版）
             */
            static async callAiYiJingApi(info, options = {}) {
                const cacheKey = this._generateCacheKey(info, options);
                
                // 检查缓存
                if (this.cache.has(cacheKey)) {
                    const cached = this.cache.get(cacheKey);
                    if (Date.now() - cached.timestamp < this.CACHE_DURATION) {
                        console.log("使用缓存数据");
                        return cached.data;
                    }
                }

                const content_text = this._generateEnhancedPrompt(info, options);
                
                const requestOptions = {
                    method: "POST",
                    headers: {
                        Authorization: "Bearer sk-xziuakupoderrivcjtmpirqodwtasvnddhjmfwetquulqwbi",
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        messages: [
                            {
                                content: content_text,
                                role: "user",
                            },
                        ],
                        model: this.API_CONFIG.model,
                        temperature: options.temperature || 0.7,
                        max_tokens: options.max_tokens || 1000
                    }),
                };
                
                // 带重试机制的API调用
                return this._callWithRetry(requestOptions, cacheKey);
            }

            /**
             * 带重试机制的API调用
             */
            static async _callWithRetry(requestOptions, cacheKey) {
                let lastError;
                
                for (let i = 0; i < this.API_CONFIG.retryCount; i++) {
                    try {
                        const controller = new AbortController();
                        const timeoutId = setTimeout(() => controller.abort(), this.API_CONFIG.timeout);
                        
                        const response = await fetch(this.API_CONFIG.baseUrl, {
                            ...requestOptions,
                            signal: controller.signal
                        });
                        
                        clearTimeout(timeoutId);
                        
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                        }
                        
                        const data = await response.json();
                        const result = this._parseResponse(data);
                        
                        // 缓存结果
                        this.cache.set(cacheKey, {
                            data: result,
                            timestamp: Date.now()
                        });
                        
                        return result;
                        
                    } catch (error) {
                        lastError = error;
                        console.warn(`API调用失败 (尝试 ${i + 1}/${this.API_CONFIG.retryCount}):`, error.message);
                        
                        if (i < this.API_CONFIG.retryCount - 1) {
                            // 指数退避
                            await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000));
                        }
                    }
                }
                
                throw new Error(`API调用失败，已重试${this.API_CONFIG.retryCount}次: ${lastError.message}`);
            }

            /**
             * 解析API响应
             */
            static _parseResponse(response) {
                try {
                    const content = response.choices[0].message.content;
                    const parsed = JSON.parse(content);
                    
                    // 验证必要字段
                    if (!parsed.today_luck || !parsed.jx || !parsed.info) {
                        throw new Error("API返回数据格式不完整");
                    }
                    
                    return {
                        ...parsed,
                        timestamp: Date.now(),
                        version: "4.0.1"
                    };
                } catch (error) {
                    console.error("JSON解析错误:", error);
                    console.log("原始响应数据:", response.choices[0].message.content);
                    throw new Error("API返回数据格式错误");
                }
            }

            /**
             * 生成增强版提示文本
             */
            static _generateEnhancedPrompt(info, options = {}) {
                const analysisType = options.analysisType || "comprehensive";
                const includeElements = options.includeElements || true;
                const includeTimeAnalysis = options.includeTimeAnalysis || true;
                
                let prompt = `请你扮演一位精通易学的老师，根据我提供的信息进行${analysisType}分析。`;
                
                if (includeTimeAnalysis) {
                    prompt += `分析步骤：
1、根据给出的日期进行当日黄道信息获取
2、分析当前时辰的五行属性和能量状态
3、结合用户信息进行个人运势分析
4、对指定方向进行吉凶判断
5、提供具体的运势指导和解挂方法`;
                }
                
                if (includeElements) {
                    prompt += `
6、分析五行相生相克关系
7、提供颜色、数字、方位等开运建议`;
                }
                
                prompt += `
推算结果以JSON格式返回，格式如下：
{
    "today_luck": "今日运势描述",
    "jx": "吉/凶",
    "info": "具体运势分析",
    "jie": "解挂方法或开运建议",
    "elements": {
        "wood": "木属性分析",
        "fire": "火属性分析", 
        "earth": "土属性分析",
        "metal": "金属性分析",
        "water": "水属性分析"
    },
    "lucky_colors": ["颜色1", "颜色2"],
    "lucky_numbers": [数字1, 数字2],
    "avoid_directions": ["避免方向1", "避免方向2"],
    "best_time": "最佳出行时间",
    "energy_level": 85
}`;
                
                prompt += `\n\n本次分析信息：${info}`;
                
                return prompt;
            }

            /**
             * 生成缓存键
             */
            static _generateCacheKey(info, options) {
                return btoa(JSON.stringify({ info, options }));
            }

            /**
             * 清除缓存
             */
            static clearCache() {
                this.cache.clear();
                console.log("缓存已清除");
            }

            /**
             * 获取缓存统计
             */
            static getCacheStats() {
                return {
                    size: this.cache.size,
                    maxAge: this.CACHE_DURATION,
                    entries: Array.from(this.cache.keys())
                };
            }

            /**
             * 批量分析多个方向
             */
            static async batchAnalyze(info, directions) {
                const promises = directions.map(direction => 
                    this.callAiYiJingApi(`${info}，方向：${direction}`)
                );
                
                try {
                    const results = await Promise.allSettled(promises);
                    return results.map((result, index) => ({
                        direction: directions[index],
                        success: result.status === 'fulfilled',
                        data: result.status === 'fulfilled' ? result.value : null,
                        error: result.status === 'rejected' ? result.reason.message : null
                    }));
                } catch (error) {
                    throw new Error(`批量分析失败: ${error.message}`);
                }
            }
        }

        // 全局变量
        window.currentDirection = "";
        window.apiResult = null;
        window.needleRotation = 0;

        // 方向到角度的映射
        const directionAngles = {
            '北': 0,
            '东北': 45,
            '东': 90,
            '东南': 135,
            '南': 180,
            '西南': 225,
            '西': 270,
            '西北': 315
        };

        // 五行颜色映射
        const elementColors = {
            'wood': '#27ae60',
            'fire': '#e74c3c',
            'earth': '#f39c12',
            'metal': '#95a5a6',
            'water': '#3498db'
        };

        // 五行中文名称
        const elementNames = {
            'wood': '木',
            'fire': '火',
            'earth': '土',
            'metal': '金',
            'water': '水'
        };

        /**
         * 获取当前时间（东八区）
         */
        function getCurrentTime() {
            const now = new Date();
            // 直接使用本地时间，因为用户在中国
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        /**
         * 转换时辰
         */
        function convertToChineseTime(hour, minute) {
            const times = ['子时', '丑时', '寅时', '卯时', '辰时', '巳时', '午时', '未时', '申时', '酉时', '戌时', '亥时'];
            const timeIndex = Math.floor((hour + 1) / 2) % 12;
            const minuteMark = minute < 15 ? '一刻' : minute < 30 ? '二刻' : minute < 45 ? '三刻' : '四刻';
            return `${times[timeIndex]}${minuteMark}`;
        }

        /**
         * 获取黄道信息
         */
        function getHuangDaoInfo(date) {
            const day = date.getDate();
            const month = date.getMonth() + 1;
            const sum = day + month;
            return [1, 3, 5, 7, 9, 11, 13].includes(sum % 14) ? "黄道吉日" : "黑道凶日";
        }

        /**
         * 计算能量等级
         */
        function calculateEnergyLevel(hour, minute) {
            const baseEnergy = 50;
            const timeBonus = Math.sin((hour + minute / 60) * Math.PI / 12) * 30;
            const randomFactor = Math.random() * 20;
            return Math.max(0, Math.min(100, Math.round(baseEnergy + timeBonus + randomFactor)));
        }

        /**
         * 更新时间信息
         */
        function updateTimeInfo() {
            const currentTime = getCurrentTime();
            const now = new Date();
            const hour = now.getHours();
            const minute = now.getMinutes();
            
            document.getElementById('current-time').textContent = currentTime;
            document.getElementById('shi-chen').textContent = convertToChineseTime(hour, minute);
            document.getElementById('huang-dao').textContent = getHuangDaoInfo(now);
            
            const energyLevel = calculateEnergyLevel(hour, minute);
            document.getElementById('energy-level').textContent = `${energyLevel}%`;
            
            return { currentTime, energyLevel };
        }

        /**
         * 旋转罗盘指针
         */
        function rotateNeedle(direction) {
            const angle = directionAngles[direction];
            const needle = document.getElementById('needle');
            const centerText = document.getElementById('center-text');
            
            window.needleRotation = angle;
            // 确保指针从中心点旋转，并保持正确的定位
            needle.style.transform = `translate(-50%, -100%) rotate(${angle}deg)`;
            centerText.textContent = direction;
            
            console.log(`指针旋转到方向: ${direction}, 角度: ${angle}度`);
        }

        /**
         * 更新结果显示
         */
        function updateResultDisplay() {
            if (!window.apiResult || !window.currentDirection) return;
            
            const result = window.apiResult;
            document.getElementById('selected-direction').textContent = window.currentDirection;
            
            // 更新吉凶标志
            const jxBadge = document.getElementById('jx-badge');
            jxBadge.textContent = result.jx || '-';
            jxBadge.className = 'jx-badge';
            if (result.jx === "吉") {
                jxBadge.classList.add('ji');
            } else if (result.jx === "凶") {
                jxBadge.classList.add('xiong');
            }
            
            // 更新内容
            document.getElementById('result-content').textContent = result.info || '无详细信息';
            document.getElementById('jie-method').textContent = result.jie || '-';
            
            // 显示结果容器
            document.getElementById('result-container').style.display = 'block';
            
            // 更新数据可视化
            updateVisualization(result);
        }

        /**
         * 更新数据可视化
         */
        function updateVisualization(result) {
            // 更新能量等级
            const energyLevel = result.energy_level || 50;
            const energyFill = document.getElementById('energy-fill');
            const energyText = document.getElementById('energy-text');
            
            energyFill.style.width = `${energyLevel}%`;
            energyText.textContent = `${energyLevel}%`;
            
            // 更新五行分析
            if (result.elements) {
                const elementsGrid = document.getElementById('elements-grid');
                elementsGrid.innerHTML = '';
                
                Object.entries(result.elements).forEach(([key, value]) => {
                    const elementDiv = document.createElement('div');
                    elementDiv.className = 'element-item';
                    elementDiv.style.backgroundColor = elementColors[key] + '20';
                    elementDiv.style.border = `1px solid ${elementColors[key]}`;
                    elementDiv.innerHTML = `
                        <div style="color: ${elementColors[key]}; font-weight: bold;">${elementNames[key]}</div>
                        <div style="font-size: 0.8rem; margin-top: 5px;">${value}</div>
                    `;
                    elementsGrid.appendChild(elementDiv);
                });
            }
            
            // 更新开运建议
            const luckyInfo = document.getElementById('lucky-info');
            let luckyHtml = '';
            
            if (result.lucky_colors && result.lucky_colors.length > 0) {
                luckyHtml += `<div style="margin-bottom: 10px;"><strong>幸运颜色:</strong> ${result.lucky_colors.join(', ')}</div>`;
            }
            
            if (result.lucky_numbers && result.lucky_numbers.length > 0) {
                luckyHtml += `<div style="margin-bottom: 10px;"><strong>幸运数字:</strong> ${result.lucky_numbers.join(', ')}</div>`;
            }
            
            if (result.best_time) {
                luckyHtml += `<div><strong>最佳时间:</strong> ${result.best_time}</div>`;
            }
            
            luckyInfo.innerHTML = luckyHtml || '<div>暂无开运建议</div>';
            
            // 显示可视化容器
            document.getElementById('visualization').style.display = 'grid';
        }

        /**
         * 锁定界面
         */
        function lockUI() {
            document.querySelectorAll('button, input').forEach(el => {
                el.disabled = true;
            });
            
            const resultContent = document.getElementById('result-content');
            resultContent.innerHTML = '<div class="loading"><div class="spinner"></div><div style="margin-left: 15px;">正在分析中，请稍候...</div></div>';
        }

        /**
         * 解锁界面
         */
        function unlockUI() {
            document.querySelectorAll('button, input').forEach(el => {
                el.disabled = false;
            });
        }

        /**
         * 调用AI分析
         */
        window.aiYiJingChuXing = async function(userInfo, direction) {
            try {
                lockUI();
                
                const timeInfo = updateTimeInfo();
                const info = userInfo 
                    ? `${userInfo}，方向：${direction}，当前时间：${timeInfo.currentTime}，能量等级：${timeInfo.energyLevel}%` 
                    : `方向：${direction}，当前时间：${timeInfo.currentTime}，能量等级：${timeInfo.energyLevel}%`;
                
                console.log("发送信息:", info);
                
                // 先尝试调用API
                try {
                    const result = await ApiService.callAiYiJingApi(info, {
                        analysisType: 'comprehensive',
                        includeElements: true,
                        includeTimeAnalysis: true
                    });
                    
                    console.log("API返回结果:", result);
                    window.apiResult = result;
                } catch (apiError) {
                    console.warn("API调用失败，使用模拟数据:", apiError);
                    // 使用模拟数据
                    window.apiResult = generateMockResult(direction, timeInfo.energyLevel);
                }
                
                window.currentDirection = direction;
                updateResultDisplay();
                
            } catch (error) {
                console.error("分析失败:", error);
                alert("分析失败，请稍后再试");
            } finally {
                unlockUI();
            }
        };

        /**
         * 生成模拟结果（用于测试）
         */
        function generateMockResult(direction, energyLevel) {
            const mockResults = {
                '东': { jx: '吉', info: '东方为木，生机勃勃，适合出行，事业顺利', jie: '佩戴绿色饰品，选择绿色出行工具' },
                '南': { jx: '吉', info: '南方为火，热情似火，人际关系佳，财运亨通', jie: '穿着红色衣物，选择红色装饰' },
                '西': { jx: '凶', info: '西方为金，今日金气过旺，易有口舌是非', jie: '避免白色物品，佩戴黄色饰品化解' },
                '北': { jx: '吉', info: '北方为水，智慧如海，学习工作顺利', jie: '多接触蓝色物品，保持冷静' },
                '东南': { jx: '吉', info: '东南为巽，风调雨顺，财运亨通', jie: '选择绿色或蓝色装饰' },
                '东北': { jx: '凶', info: '东北为艮，山重水复，阻碍较多', jie: '避免黄色物品，选择红色化解' },
                '西南': { jx: '吉', info: '西南为坤，厚德载物，家庭和睦', jie: '多接触黄色物品，保持平和心态' },
                '西北': { jx: '凶', info: '西北为乾，刚强过甚，易有冲突', jie: '避免金属物品，选择绿色调和' }
            };
            
            const baseResult = mockResults[direction] || { jx: '中', info: '此方向运势平稳', jie: '保持平常心即可' };
            
            return {
                today_luck: `今日${direction}方运势${baseResult.jx === '吉' ? '大吉' : baseResult.jx === '凶' ? '不利' : '平稳'}`,
                jx: baseResult.jx,
                info: baseResult.info,
                jie: baseResult.jie,
                elements: {
                    wood: '木属性：生机勃勃，适合发展',
                    fire: '火属性：热情活跃，人际关系佳',
                    earth: '土属性：稳重踏实，财运稳定',
                    metal: '金属性：刚强果断，事业有成',
                    water: '水属性：智慧深沉，学习能力强'
                },
                lucky_colors: ['绿色', '蓝色'],
                lucky_numbers: [3, 8],
                best_time: '上午9-11点',
                energy_level: energyLevel
            };
        }

        /**
         * 刷新数据
         */
        window.refreshData = function() {
            if (window.currentDirection) {
                const userInfo = document.getElementById('info-input').value;
                aiYiJingChuXing(userInfo, window.currentDirection);
            } else {
                alert("请先选择一个方向");
            }
        };

        /**
         * 分析数据
         */
        window.analyzeData = function() {
            if (window.currentDirection) {
                const userInfo = document.getElementById('info-input').value;
                aiYiJingChuXing(userInfo, window.currentDirection);
            } else {
                alert("请先选择一个方向");
            }
        };

        /**
         * 清除缓存
         */
        window.clearCache = function() {
            ApiService.clearCache();
            alert("缓存已清除");
        };

        /**
         * 批量分析
         */
        window.batchAnalyze = async function() {
            const userInfo = document.getElementById('info-input').value;
            const directions = ['东', '南', '西', '北', '东南', '东北', '西南', '西北'];
            
            try {
                lockUI();
                const results = await ApiService.batchAnalyze(userInfo, directions);
                
                console.log("批量分析结果:", results);
                
                // 显示第一个成功的结果
                const firstSuccess = results.find(r => r.success);
                if (firstSuccess) {
                    window.apiResult = firstSuccess.data;
                    window.currentDirection = firstSuccess.direction;
                    rotateNeedle(firstSuccess.direction);
                    updateResultDisplay();
                }
                
            } catch (error) {
                console.error("批量分析失败:", error);
                alert("批量分析失败，请稍后再试");
            } finally {
                unlockUI();
            }
        };

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，开始初始化...');
            
            // 立即更新时间信息
            updateTimeInfo();
            console.log('时间信息已更新');
            
            // 初始化指针位置
            const needle = document.getElementById('needle');
            if (needle) {
                needle.style.transform = 'translate(-50%, -100%) rotate(0deg)';
                console.log('指针位置已初始化');
            }
            
            // 设置定时器每分钟更新时间
            setInterval(updateTimeInfo, 60000);
            
            // 为方向标签添加点击事件
            const directionLabels = document.querySelectorAll('.direction-label');
            console.log('找到方向标签数量:', directionLabels.length);
            
            directionLabels.forEach((label, index) => {
                label.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('点击方向标签:', this.getAttribute('data-direction'));
                    
                    const direction = this.getAttribute('data-direction');
                    window.currentDirection = direction;
                    rotateNeedle(direction);
                    
                    const userInfo = document.getElementById('info-input').value;
                    aiYiJingChuXing(userInfo, direction);
                });
            });
            
            // 为罗盘中心添加点击事件
            const compass = document.getElementById('compass');
            if (compass) {
                compass.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('点击罗盘中心');
                    
                    // 可以添加随机选择方向的逻辑
                    const directions = Object.keys(directionAngles);
                    const randomDirection = directions[Math.floor(Math.random() * directions.length)];
                    window.currentDirection = randomDirection;
                    rotateNeedle(randomDirection);
                    
                    const userInfo = document.getElementById('info-input').value;
                    aiYiJingChuXing(userInfo, randomDirection);
                });
            }
            
            // 为分析按钮添加点击事件
            const analyzeBtn = document.getElementById('analyze-btn');
            if (analyzeBtn) {
                analyzeBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    console.log('点击分析按钮');
                    analyzeData();
                });
            }
            
            console.log('初始化完成');
        });
    </script>
</body>
</html>
